package com.xingkeduo.gateway.filter;

import org.springframework.cloud.gateway.filter.GatewayFilter;
import org.springframework.cloud.gateway.filter.factory.AbstractGatewayFilterFactory;
import org.springframework.core.io.buffer.DataBuffer;
import org.springframework.http.HttpHeaders;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;

import com.xingkeduo.util.pojo.exception.AuthorityException;
import com.xingkeduo.util.tool.ReturnUtil;

import reactor.core.publisher.Mono;

/**
 * sign验证
 * 
 * @author GJ
 * @time 2018年12月4日 下午1:27:11
 * @description
 */
@Component
public class SignCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<Object>
{
	@Override
	public GatewayFilter apply(Object config)
	{
		return (exchange, chain) -> {
			// return chain.filter(exchange);
			ServerHttpRequest request = exchange.getRequest();
			String sign = request.getQueryParams().getFirst("sign");
			System.out.println("sign======" + sign);
			// 校验jwtToken的合法性
			if (sign != null)
				// 合法
				return chain.filter(exchange);

			// 不合法
			ServerHttpResponse response = exchange.getResponse();
			// 设置headers
			HttpHeaders httpHeaders = response.getHeaders();
			httpHeaders.add("Content-Type", "application/json; charset=UTF-8");
			httpHeaders.add("Cache-Control", "no-store, no-cache, must-revalidate, max-age=0");

			// 设置body
			ReturnUtil returnUtil = new ReturnUtil();
			DataBuffer bodyDataBuffer = response.bufferFactory().wrap(returnUtil
					.getException(AuthorityException.Type.SIGN.getCode(), AuthorityException.Type.SIGN.getMsg())
					.getBytes());
			return response.writeWith(Mono.just(bodyDataBuffer));
		};
	}
}
